<template>
<div>
    <el-upload
    v-if="isUpload"
    class="avatar-uploader"
    action="https://jsonplaceholder.typicode.com/posts/"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="httpRequest">
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-progress v-else :width="178" type="circle" :percentage="percentage"></el-progress>
</div>
</template>

<script lang="ts">
import Vue from 'vue'
import { upload } from '@/services/course'
import { Form } from 'element-ui'
export default Vue.extend({
  name: 'courseImg',
  props: {
    value: {
      type: String
    }
  },
  data () {
    return {
      imageUrl: '',
      isUpload: true,
      percentage: 0
    }
  },
  methods: {
    // handleAvatarSuccess (res: any, file: any) {
    //   this.imageUrl = URL.createObjectURL(file.raw)
    // },
    beforeAvatarUpload (file: any) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async httpRequest ({ file }: any) {
      console.log(file, '-----')
      this.isUpload = false
      const fd = new FormData()
      fd.append('file', file)
      const { data } = await upload(fd, (e: any) => {
        this.percentage = Math.floor(e.loaded / e.total * 100)
      })
      this.isUpload = true
      this.percentage = 0
      this.$emit('input', data.name)
    }
  }
})
</script>
<style lang='scss' scoped>
::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
::v-deep  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
::v-deep  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
::v-deep  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
